package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户名
     *
     * @param username 用户名
     * @return
     */
    @Override
    public User findByUserName(String username) {
        log.info("根据用户名查询用户信息");
        log.info("用户名:{}", username);
        User user = userMapper.findByUserName(username);
        return user;
    }

    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public Result register(String username, String password) {
        //对密码进行md5加密
        String md5String = Md5Util.getMD5String(password);
        log.info("加密后的密码:{}", md5String);
        Boolean flag = userMapper.addUser(username, md5String);
        if (flag) {
            return Result.success();
        }
        return Result.error("注册失败！");
    }

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     */
    @Override
    public Boolean update(User user) {
        log.info("用户信息:{}",user);
        user.setUpdateTime(LocalDateTime.now());
        Boolean b = userMapper.upDate(user);
        return b;
    }

    /**
     * 更新用户头像
     *
     * @param avatarUrl 头像地址
     */
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }

    @Override
    public void updatePwd(String newPwd, Integer id) {
        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);
    }
}
